import requests
from bs4 import BeautifulSoup
import json
import re
import base64


class SciClient:
    def __init__(self, domain, loginName, loginPwd, clientId=''):
        s = requests.session()
        self.session = s
        self.domain = domain
        self.clientId = clientId
        loginData = {
            "clientId": "sso",
            "username": loginName,
            "password": base64.b64encode(loginPwd.encode('utf-8'))
        }

        loginHead = {
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "Accept": "application/json",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36"
        }

        loginUrl = domain + '/sso/auth/login'

        print('登录url: %s, data: %s' % (loginUrl, loginData))

        loginRe = s.post(loginUrl, data=loginData, headers=loginHead)
        if (requests.codes.ok == loginRe.status_code):
            resultObj = json.loads(loginRe.content)
            if (resultObj['code'] == 200):
                print('登录成功: %s' % loginRe.text)
                cookieItems = resultObj['data']['urlLst']
                tokenId = resultObj['data']['tokenId']
                cookieParams = {
                    'tokenId': tokenId
                }
                for item in cookieItems:
                    try:
                        s.get(item, params=cookieParams)

                    except BaseException as e:
                        print('设置cookie失败: %s' % item)

                if clientId:
                    selectClientData = {
                        'nodeId': clientId
                    }
                    s.post(domain + '/master/customer/updateCustomerSelected', data=selectClientData)

                # 获取系统运营中心
                ocQueryData = {
                    'pl.nodeCode': 100,
                    'pl.nodeTypes': 'OP_OC',
                    'pl.currentPage': 1,
                    'pl.pageSize': 50
                }
                ocPage = s.post(domain + '/master/org/platform/doQuery', data=ocQueryData)
                if requests.codes.ok == ocPage.status_code:
                    ocEl = BeautifulSoup(ocPage.text, 'html.parser')
                    octrs = ocEl.select('div[class="table-panel-content"] table tr')
                    ocDict = {}
                    for ocTr in octrs:
                        ocOidOrId = ocTr.find('td', attrs={'name': 'nodeId'}).find('a')
                        ocOidReg = ".*?\('(.*?)',.*?"
                        ocId = ocOidOrId.string
                        ocOid = re.match(ocOidReg, ocOidOrId.attrs['href']).group(1)
                        ocName = ocTr.find('td', attrs={'name': 'nodeName'}).attrs['title']

                        oc = {'ocId': ocId, 'ocOid': ocOid, 'ocName': ocName}
                        ocDict[ocId] = oc
                    self.ocDict = ocDict
            else:
                print('登录失败: %s' % loginRe.text)
        else:
            print('登录失败: %s' % loginRe.text)


if __name__ == '__main__':

    client = SciClient(domain='http://localhost:8083', loginName='lyon', loginPwd='PASSWORD', clientId='HT01')





